﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace Client
{
    public class ConnectToServer : IDisposable
    {
        private String _serverIp;
        private Int32 _port;

        private TcpClient _serverSocket;
        private NetworkStream _netStream;
        private StreamWriter _swriter;
        private static StreamReader _sreader;
        private static List<String> beskeder = new List<string>();

        public ConnectToServer(String server, Int32 port)
        {
            _serverIp = server;
            _port = port;
            OpenConnection();

        }

        private void OpenConnection()
        {
            _serverSocket = new TcpClient(_serverIp, _port);
            _netStream = _serverSocket.GetStream();
            _swriter = new StreamWriter(_netStream);
            _sreader = new StreamReader(_netStream);
        }

        private void CloseConnection()
        {
            _swriter.Close();
            _sreader.Close();
            _netStream.Close();
            _serverSocket.Close();
            _serverSocket = null;
        }

        public void SendMessage(String message)
        {
            _swriter.WriteLine(message);
            _swriter.Flush();
            
        }

        public static void ReciveMessage()
        {
                while (true)
                {
                    Console.WriteLine(_sreader.ReadLine());        
                }
        }
        public String LæsBesked()
        {
            
            lock (beskeder)
            {
                String temp = "";
                foreach (string besked in beskeder)
                {
                    temp += besked+"\r\n";
                }
                beskeder.Clear();
                return temp;

            }
        }

        public void Dispose()
        {
            CloseConnection();
        }
    }
}